package com.demo.websocket.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.messaging.AbstractSubProtocolEvent;
import org.springframework.web.socket.messaging.SessionConnectEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

/**
 * 监听记录session websoket
 */
// AbstractSubProtocolEvent
public class STOMPConnectEventListener implements ApplicationListener<AbstractSubProtocolEvent> {
	@Autowired
	SocketSessionRegistry webAgentSessionRegistry;

	// SessionDisconnectEvent
	// SessionConnectedEvent
	// SessionConnectEvent
	// SessionSubscribeEvent
	// SessionUnsubscribeEvent

	// @Override
	// public void onApplicationEvent(SessionConnectEvent event) {
	// StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
	// // login get from browser
	// String name = sha.getNativeHeader("login").get(0);
	// String sessionId = sha.getSessionId();
	// webAgentSessionRegistry.registerSessionId(name, sessionId);
	// }

	@Override
	public void onApplicationEvent(AbstractSubProtocolEvent event) {
		if (event instanceof SessionConnectEvent) {
			System.err.println("SessionConnectEvent");
			StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
			// login get from browser
			String name = sha.getNativeHeader("login").get(0);
			String sessionId = sha.getSessionId();
			webAgentSessionRegistry.registerSessionId(name, sessionId);
		} else if (event instanceof SessionDisconnectEvent) {
			System.err.println("SessionDisconnectEvent");
			webAgentSessionRegistry.unregisterSessionId(((SessionDisconnectEvent) event).getSessionId());
		}

	}
}
